package gdut.imis.Utils;

import gdut.imis.vo.UserLoginVo;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description 自定义权限校验
 * @Author JiaFu
 * @Date 2023/4/16 22:00
 */
@Component("cp")
public class CheckPermissions {
    public boolean hasPermission(String permission) {
        //获取当前用户权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginVo userLoginVo = (UserLoginVo) authentication.getPrincipal();
        List<String> permissions = userLoginVo.getPermissions();
        //判断用户是否拥有相应权限
        return permissions.contains(permission);
    }

    //拥有其中一个权限便可以访问
    public boolean hasOneOfPermissions(String... permissions) {
        //获取当前用户权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserLoginVo userLoginVo = (UserLoginVo) authentication.getPrincipal();
        List<String> permissionList = userLoginVo.getPermissions();
        //判断用户是否拥有相应权限
        boolean flag = false;
        for (String permission : permissions) {
            boolean contains = permissionList.contains(permission);
            if (contains) {
                flag = true;
                break;
            }
        }
        return flag;
    }
}
